import React, { useRef, useEffect } from 'react'
import { dragBus } from '../utils/dragBus'
import type { DragComponentData } from '../types'

export interface SourceBoxProps {
  children: React.ReactNode
  data: DragComponentData
  type?: string // 源类型，用于区分不同的拖拽源
  onDragStart?: () => void
  onDragEnd?: () => void
}

export const SourceBox: React.FC<SourceBoxProps> = ({ 
  children, 
  data, 
  type,
  onDragStart,
  onDragEnd
}) => {
  const dragRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (dragRef.current) {
      dragRef.current.draggable = true

      const handleDragStart = (e: DragEvent) => {
        const payload = {
          sourceData: data,
          sourceType: type
        }
        
        dragBus.setDrag(dragRef.current!, payload)
        e.dataTransfer?.setData('text/plain', JSON.stringify(payload))
        
        onDragStart?.()
      }

      const handleDragEnd = () => {
        dragBus.reset()
        onDragEnd?.()
      }

      dragRef.current.addEventListener('dragstart', handleDragStart)
      dragRef.current.addEventListener('dragend', handleDragEnd)

      return () => {
        if (dragRef.current) {
          dragRef.current.removeEventListener('dragstart', handleDragStart)
          dragRef.current.removeEventListener('dragend', handleDragEnd)
        }
      }
    }
  }, [data, type, onDragStart, onDragEnd])

  return (
    <div ref={dragRef} style={{ width: '100%' }}>
      {children}
    </div>
  )
}